<template>
  <div class="admin-visitors">
    <div class="page-header">
      <h2>观众管理</h2>
      <div class="header-actions">
        <el-button v-if="hasPermission('visitor_add')" type="primary" @click="openAdd">
          添加观众
        </el-button>

      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input v-model="searchForm.keyword" placeholder="搜索姓名/公司" clearable @input="handleSearch" />
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.source" placeholder="来源" clearable @change="handleSearch">
            <el-option label="官网" value="website" />
            <el-option label="合作伙伴" value="partner" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.status" placeholder="状态" clearable @change="handleSearch">
            <el-option label="正常" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button @click="exportExcel">导出</el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 观众列表 -->
    <el-table :data="visitorsList" style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="isRead" label="是否新注册" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.isRead == 1 ? 'success' : 'info'">
            {{ scope.row.isRead == 1 ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="姓名" />
      <el-table-column prop="gender" label="性别">
        <template #default="scope">
          {{ getOptionLabel(genderOptions, scope.row.gender) }}
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号码" />
      <el-table-column prop="email" label="邮箱地址" />
      <el-table-column prop="company" label="公司名称" />
      <el-table-column prop="position" label="职位" />
      <el-table-column prop="industry" label="行业类型" />
      <el-table-column prop="companySize" label="公司规模">
        <template #default="scope">
          {{ getOptionLabel(companySizeOptions, scope.row.companySize) }}
        </template>
      </el-table-column>
      <el-table-column prop="interests" label="关注产品" />
      <el-table-column prop="visitPurpose" label="参观目的">
        <template #default="scope">
          {{ calacutedVisitPurpose(scope.row.visitPurpose) }}
        </template>
      </el-table-column>

      <el-table-column prop="visitDate" label="参观日期" />
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-tag :type="scope.row.status === 'active' ? 'success' : 'danger'">
            {{ scope.row.status === 'active' ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="specialRequirements" label="特殊需求" />
      <el-table-column prop="createdTime" label="注册时间" />
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="scope">
          <el-button v-if="hasPermission('visitor_view')" size="small" @click="viewVisitor(scope.row)">
            查看
          </el-button>
          <el-button v-if="hasPermission('visitor_edit')" size="small" type="primary" @click="editVisitor(scope.row)">
            编辑
          </el-button>
          <el-button v-if="hasPermission('visitor_delete')" size="small" type="danger"
            @click="deleteVisitor(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    <!-- 添加/编辑观众对话框 -->
    <el-dialog v-model="showAddDialog" :title="editingVisitor ? '编辑观众' : '添加观众'" width="700px">
      <el-form :model="visitorForm" :rules="visitorRules" ref="visitorFormRef" label-width="110px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="visitorForm.name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="visitorForm.gender" placeholder="选择性别" clearable>
                <el-option v-for="option in genderOptions" :key="option.value" :label="option.label"
                  :value="option.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公司" prop="company">
              <el-input v-model="visitorForm.company" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职位" prop="position">
              <el-input v-model="visitorForm.position" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="visitorForm.phone" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱地址" prop="email">
              <el-input v-model="visitorForm.email" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="行业类型" prop="industry">
              <el-input v-model="visitorForm.industry" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司规模" prop="companySize">
              <el-select v-model="visitorForm.companySize" placeholder="选择公司规模" clearable>
                <el-option v-for="option in companySizeOptions" :key="option.value" :label="option.label"
                  :value="option.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="参观日期" prop="visitDate">
              <el-date-picker v-model="visitorForm.visitDate" type="date" placeholder="请选择参观日期"
                value-format="YYYY-MM-DD" style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="参观目的" prop="visitPurpose">
              <el-select v-model="visitorForm.visitPurpose" multiple placeholder="选择参观目的" collapse-tags
                collapse-tags-tooltip clearable>
                <el-option v-for="option in visitPurposeOptions" :key="option.value" :label="option.label"
                  :value="option.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="关注产品" prop="interests">
              <el-input v-model="visitorForm.interests" type="textarea" :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="特殊需求" prop="specialRequirements">
              <el-input v-model="visitorForm.specialRequirements" type="textarea" :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="visitorForm.status">
            <el-radio label="active">正常</el-radio>
            <el-radio label="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelEdit">取消</el-button>
        <el-button type="primary" @click="saveVisitor" :loading="saving">保存</el-button>
      </template>
    </el-dialog>

    <!-- 查看观众详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="查看观众详情" width="700px">
      <div v-if="viewingVisitor" class="visitor-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="姓名">{{ viewingVisitor.name || '-' }}</el-descriptions-item>
          <el-descriptions-item label="性别">
            {{ getOptionLabel(genderOptions, viewingVisitor.gender) || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="公司名称">{{ viewingVisitor.company || '-' }}</el-descriptions-item>
          <el-descriptions-item label="职位">{{ viewingVisitor.position || '-' }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ viewingVisitor.phone || '-' }}</el-descriptions-item>
          <el-descriptions-item label="邮箱地址">{{ viewingVisitor.email || '-' }}</el-descriptions-item>
          <el-descriptions-item label="行业类型">{{ viewingVisitor.industry || '-' }}</el-descriptions-item>
          <el-descriptions-item label="公司规模">
            {{ getOptionLabel(companySizeOptions, viewingVisitor.companySize) || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="参观目的">{{ calacutedVisitPurpose(viewingVisitor.visitPurpose) || '-'
            }}</el-descriptions-item>
          <el-descriptions-item label="参观日期">{{ viewingVisitor.visitDate || '-' }}</el-descriptions-item>

          <el-descriptions-item label="状态">
            <el-tag :type="viewingVisitor.status === 'active' ? 'success' : 'danger'">
              {{ viewingVisitor.status === 'active' ? '正常' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="关注产品">
            {{ viewingVisitor.interests || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="特殊需求">
            {{ viewingVisitor.specialRequirements || '-' }}
          </el-descriptions-item>

          <el-descriptions-item label="注册时间">{{ viewingVisitor.createdTime || '-' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="viewDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { visitorApi } from '@/api/admin'
import request from '@/utils/request'
import { useExcelExport } from '@/hooks/useExcelExport'

export default {
  name: 'AdminVisitors',
  setup() {
    const loading = ref(false)
    const saving = ref(false)
    const showAddDialog = ref(false)
    const editingVisitor = ref(null)
    const visitorFormRef = ref(null)
    const viewDialogVisible = ref(false)
    const viewingVisitor = ref(null)

    const companySizeOptions = ref([
      { label: '1-50人', value: 'small' },
      { label: '51-200人', value: 'medium' },
      { label: '201-1000人', value: 'large' },
      { label: '1000人以上', value: 'enterprise' },
    ])
    const visitPurposeOptions = ref([
      { label: '了解新技术', value: 'technology' },
      { label: '商务合作', value: 'cooperation' },
      { label: '寻找供应商', value: 'supplier' },
      { label: '市场调研', value: 'research' },
      { label: '学习交流', value: 'learning' },
    ])
    const genderOptions = ref([
      { label: '男', value: 'male' },
      { label: '女', value: 'female' },
    ])

    // 使用Excel导出hooks
    const { exportListData, columnWidthPresets, mapperPresets } = useExcelExport()

    // 搜索表单
    const searchForm = reactive({
      keyword: '',
      source: '',
      status: ''
    })

    // 观众表单
    const visitorForm = reactive({
      name: '',
      gender: '',
      company: '',
      position: '',
      phone: '',
      email: '',
      industry: '',
      companySize: '',
      visitPurpose: [],
      visitDate: '',
      source: 'website',
      interests: '',
      specialRequirements: '',
      remark: '',
      status: 'active'
    })

    // 表单验证规则
    const visitorRules = {
      name: [
        { required: true, message: '请输入姓名', trigger: 'blur' }
      ],
      gender: [
        { required: true, message: '请选择性别', trigger: 'change' }
      ],
      company: [
        { required: true, message: '请输入公司名称', trigger: 'blur' }
      ],
      position: [
        { required: true, message: '请输入职位', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入联系电话', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      industry: [
        { required: true, message: '请输入行业类型', trigger: 'blur' }
      ],
      companySize: [
        { required: true, message: '请选择公司规模', trigger: 'change' }
      ],
      visitPurpose: [
        { required: true, message: '请选择参观目的', trigger: 'change' }
      ],
      visitDate: [
        { required: true, message: '请选择参观日期', trigger: 'change' }
      ],
      source: [
        { required: true, message: '请选择来源', trigger: 'change' }
      ]
    }

    // 分页
    const pagination = reactive({
      current: 1,
      size: 20,
      total: 0
    })

    // 观众数据列表
    const visitorsList = ref([])

    const calacutedVisitPurpose = (visitPurpose) => {
      if (!visitPurpose || (Array.isArray(visitPurpose) && visitPurpose.length === 0)) {
        return ''
      }

      const values = Array.isArray(visitPurpose)
        ? visitPurpose
        : String(visitPurpose)
          .split(',')
          .map((item) => item.trim())
          .filter(Boolean)

      const labels = values
        .map((item) => visitPurposeOptions.value.find((option) => option.value === item)?.label)
        .filter(Boolean)

      if (labels.length > 0) {
        return labels.join(',')
      }

      return values.join(',')
    }

    const getOptionLabel = (optionsRef, value) => {
      if (!optionsRef || !optionsRef.value) return value || ''
      const option = optionsRef.value.find((item) => item.value === value)
      return option?.label || value || ''
    }

    // 更新已读状态并刷新列表
    const updateReadStatusAndRefresh = async (visitorId) => {
      try {
        await visitorApi.updateReadStatus(visitorId)
        // 刷新列表以更新 isRead 状态
        await loadVisitors()
      } catch (error) {
        console.error('更新已读状态失败:', error)
        // 静默失败，不影响用户操作
      }
    }

    // 权限检查
    const hasPermission = (permission) => {
      const userInfo = JSON.parse(localStorage.getItem('adminUser') || '{}')
      // 开发阶段先返回true，确保所有功能可见
      if (userInfo.permissions?.includes('all') || userInfo.userType === 'admin') return true
      return userInfo.permissions?.includes(permission) || true // 临时返回true用于测试
    }



    // 搜索
    const handleSearch = () => {
      pagination.current = 1
      loadVisitors()
    }

    // 重置搜索
    const resetSearch = () => {
      Object.assign(searchForm, {
        keyword: '',
        source: '',
        status: ''
      })
      handleSearch()
    }

    // 加载观众数据
    const loadVisitors = async () => {
      loading.value = true
      try {
        const params = {
          page: pagination.current,
          size: pagination.size,
          name: searchForm.keyword,
          company: searchForm.keyword,
          status: searchForm.status,
          source: searchForm.source,
          industry: ''
        }

        const response = await visitorApi.getVisitorPage(params)
        if (response && response.data) {
          visitorsList.value = Array.isArray(response.data.records) ? response.data.records : []
          pagination.total = response.data.total || 0
        } else {
          visitorsList.value = []
          pagination.total = 0
        }
      } catch (error) {
        console.error('加载观众数据失败:', error)
        ElMessage.error('加载数据失败')
      } finally {
        loading.value = false
      }
    }

    // 查看观众
    const viewVisitor = async (visitor) => {
      try {
        const res = await request.get(`/admin/visitor/${visitor.id}`)
        if (res && (res.code === '200' || res.code === 200)) {
          viewingVisitor.value = res.data
          viewDialogVisible.value = true

          // 标记为已读
          await updateReadStatusAndRefresh(visitor.id)
        } else {
          ElMessage.error(res?.msg || '获取观众详情失败')
        }
      } catch (e) {
        ElMessage.error('获取观众详情失败')
      }
    }

    // 编辑观众
    const editVisitor = async (visitor) => {
      editingVisitor.value = visitor
      Object.assign(visitorForm, {
        name: visitor.name,
        gender: visitor.gender || '',
        company: visitor.company,
        position: visitor.position,
        phone: visitor.phone,
        email: visitor.email,
        industry: visitor.industry || '',
        companySize: visitor.companySize || '',
        visitPurpose: Array.isArray(visitor.visitPurpose)
          ? [...visitor.visitPurpose]
          : (visitor.visitPurpose || '')
            .split(',')
            .map((item) => item.trim())
            .filter(Boolean),
        visitDate: visitor.visitDate || '',
        source: visitor.source || 'website',
        interests: visitor.interests || '',
        specialRequirements: visitor.specialRequirements || '',
        remark: visitor.remark,
        status: visitor.status || 'active'
      })
      showAddDialog.value = true

      // 标记为已读
      await updateReadStatusAndRefresh(visitor.id)
    }

    // 删除观众
    const deleteVisitor = async (visitor) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除观众 "${visitor.name}" 吗？此操作不可恢复！`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        await visitorApi.deleteVisitor(visitor.id)
        ElMessage.success('删除成功')
        loadVisitors()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }

    // 保存观众
    const saveVisitor = async () => {
      saving.value = true

      try {
        const payload = {
          ...visitorForm,
          visitPurpose: Array.isArray(visitorForm.visitPurpose)
            ? visitorForm.visitPurpose.join(',')
            : visitorForm.visitPurpose,
        }

        if (editingVisitor.value) {
          await visitorApi.updateVisitor({ ...payload, id: editingVisitor.value.id })
          ElMessage.success('观众更新成功')
        } else {
          await visitorApi.addVisitor(payload)
          ElMessage.success('观众添加成功')
        }

        showAddDialog.value = false
        editingVisitor.value = null
        resetForm()
        loadVisitors()
      } catch (error) {
        ElMessage.error('操作失败')
      } finally {
        saving.value = false
      }
    }

    // 重置表单
    const resetForm = () => {
      Object.assign(visitorForm, {
        name: '',
        gender: '',
        company: '',
        position: '',
        phone: '',
        email: '',
        industry: '',
        companySize: '',
        visitPurpose: [],
        visitDate: '',
        source: 'website',
        interests: '',
        specialRequirements: '',
        remark: '',
        status: 'active'
      })
      visitorFormRef.value?.clearValidate()
    }

    // 新增时打开对话框，重置并设置默认状态
    const openAdd = () => {
      editingVisitor.value = null
      resetForm()
      visitorForm.status = 'active'
      showAddDialog.value = true
    }

    // 取消编辑
    const cancelEdit = () => {
      showAddDialog.value = false
      editingVisitor.value = null
      resetForm()
    }



    // 分页处理
    const handleSizeChange = (size) => {
      pagination.size = size
      loadVisitors()
    }

    const handleCurrentChange = (current) => {
      pagination.current = current
      loadVisitors()
    }

    // 导出观众列表
    const exportExcel = async () => {
      // 获取数据的函数
      const fetchData = async () => {
        const params = {
          page: 1,
          size: 100000,
          name: searchForm.keyword,
          company: searchForm.keyword,
          status: searchForm.status,
          source: searchForm.source,
          industry: '',
        }
        const response = await visitorApi.getVisitorPage(params)
        return Array.isArray(response.data.records) ? response.data.records : []
      }

      const visitorColumnWidths = [
        { wch: 15 }, // 姓名
        { wch: 10 }, // 性别
        { wch: 25 }, // 公司名称
        { wch: 15 }, // 职位
        { wch: 15 }, // 联系电话
        { wch: 25 }, // 邮箱地址
        { wch: 20 }, // 行业类型
        { wch: 15 }, // 公司规模
        { wch: 30 }, // 参观目的
        { wch: 15 }, // 参观日期
        { wch: 10 }, // 状态
        { wch: 30 }, // 关注产品
        { wch: 30 }, // 特殊需求
        { wch: 20 }, // 注册时间
      ]

      const mapData = (item) => ({
        '姓名': mapperPresets.handleEmpty(item.name),
        '性别': mapperPresets.handleEmpty(getOptionLabel(genderOptions, item.gender)),
        '公司名称': mapperPresets.handleEmpty(item.company),
        '职位': mapperPresets.handleEmpty(item.position),
        '联系电话': mapperPresets.handleEmpty(item.phone),
        '邮箱地址': mapperPresets.handleEmpty(item.email),
        '行业类型': mapperPresets.handleEmpty(item.industry),
        '公司规模': mapperPresets.handleEmpty(getOptionLabel(companySizeOptions, item.companySize)),
        '参观目的': calacutedVisitPurpose(item.visitPurpose) || '-',
        '参观日期': mapperPresets.handleEmpty(item.visitDate),
        '状态': item.status === 'active' ? '正常' : '禁用',
        '关注产品': mapperPresets.handleEmpty(item.interests),
        '特殊需求': mapperPresets.handleEmpty(item.specialRequirements),
        '注册时间': mapperPresets.handleEmpty(item.createdTime),
      })

      await exportListData(
        fetchData,
        mapData,
        '观众列表',
        visitorColumnWidths,
        '观众列表'
      )
    }

    onMounted(() => {
      loadVisitors()
    })


    return {
      loading,
      saving,
      showAddDialog,
      editingVisitor,
      visitorFormRef,
      viewDialogVisible,
      viewingVisitor,
      searchForm,
      visitorForm,
      visitorRules,
      pagination,
      visitorsList,
      companySizeOptions,
      visitPurposeOptions,
      genderOptions,
      calacutedVisitPurpose,
      getOptionLabel,
      updateReadStatusAndRefresh,
      hasPermission,
      handleSearch,
      resetSearch,
      viewVisitor,
      editVisitor,
      deleteVisitor,
      saveVisitor,
      cancelEdit,
      openAdd,
      handleSizeChange,
      handleCurrentChange,
      exportExcel
    }
  }
}
</script>

<style scoped>
.admin-visitors {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #2c3e50;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }

  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style>